package com.atguigu.rwlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockDowngradingDemo
{
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();
    private final Lock writeLock = rwLock.writeLock();
    private int data = 0;

    public int readData() {
        readLock.lock();
        try {
            return data;
        } finally {
            readLock.unlock();
        }
    }

    public void updateData(int newData) {
        writeLock.lock();
        try {
            data = newData; // 更新数据
            System.out.println(Thread.currentThread().getName()+"新数据: " + newData);

            // 锁降级，（先获取读锁，再释放写锁）
            readLock.lock(); // 获取读锁
            System.out.println(Thread.currentThread().getName()+"拿读锁");
        } finally {
            writeLock.unlock(); // 释放写锁
        }

        try {
            // 在持有读锁的情况下执行其他操作，读己之所写
            int currentData = readData();
            System.out.println(Thread.currentThread().getName()+"读所写: " + currentData);
        } finally {
            readLock.unlock(); // 释放读锁
        }
    }

    public static void main(String[] args) {

        LockDowngradingDemo example = new LockDowngradingDemo();

        new Thread(() -> {
            example.updateData(42);
        }).start();

        new Thread(() -> {
            int currentData = example.readData();
            System.out.println(Thread.currentThread().getName()+"读数据: " + currentData);
        }).start();
    }
}

